Using the sf and tmap packages to overlay a
spatial object ontop of a leaflet map with an OS Maps API base map.
tmapThe tmap R
package is providing a wrapper around the JavaScript web mapping library
Leaflet.js. It allows the
visualisation of geospatial data in R on an interactive leaflet map.
library(sf)
Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
library(tmap)
Registered S3 methods overwritten by 'htmltools':
method from
print.html tools:rstudio
print.shiny.tag tools:rstudio
print.shiny.tag.list tools:rstudio
Registered S3 method overwritten by 'htmlwidgets':
method from
print.htmlwidget tools:rstudio
The legacy packages maptools, rgdal, and rgeos, underpinning this package
will retire shortly. Please refer to R-spatial evolution reports on
https://r-spatial.org/r/2023/05/15/evolution4.html for details.
This package is now running under evolution status 0
sf object from GeoPackage (GPKG)# Create an sf data.frame object from the Greenspace file
osogs <- st_read('../../data/ordnance-survey/os-open-greenspace-gb.gpkg',
layer = 'greenspace_site')
Reading layer `greenspace_site' from data source
`/cloud/project/data/ordnance-survey/os-open-greenspace-gb.gpkg' using driver `GPKG'
Simple feature collection with 150149 features and 6 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: 9819.84 ymin: 8274.57 xmax: 655229.5 ymax: 1214133
Projected CRS: OSGB 1936 / British National Grid
Using coordinate-based indexer to spatially subset by bounding box (BBOX).
# Subset the data by intersection with BBOX
# Greater London bounding box
bbox <- st_bbox(c(xmin = 503568.1996,
xmax = 561957.4962,
ymin = 155850.7975,
ymax = 200933.9026),
crs = st_crs(27700))
# Convert into a 'geometry'
bbox <- st_as_sfc(bbox)
# Spatial subsetting/filtering
osogs_filtered <- osogs[bbox, ]
# Reproject to Web Mercator (EPSG: 3857)
osogs_filtered <- st_transform(osogs_filtered, crs = 3857)
# Basic plot using tmap
p <- tm_shape(osogs_filtered) +
tm_fill(col = '#00cd6c') +
tm_layout(frame = FALSE)
# OS Maps API layer
# Example uses Light Style in Web Mercator (EPSG:3857) projection
layer <- 'Light_3857'
# OS Data Hub project API key
key <- '7UTXMMWsGjjIzcBmLdAGnMO6WEAQi9Ng'
# Define the tile server parameters for the basemap
url <- paste0('https://api.os.uk/maps/raster/v1/zxy/', layer,
'/{z}/{x}/{y}.png?key=', key)
# Change plotting mode from static to interactive
tmap_mode('view')
tmap mode set to interactive viewing
# Combine the features and base map
final_plot <- p +
tm_basemap(server = url)
final_plot